#import "RootDetectionPlugin.h"
#import <sys/stat.h>

@implementation RootDetectionPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel* channel = [FlutterMethodChannel
        methodChannelWithName:@"com.example.root_detection/check"
              binaryMessenger:[registrar messenger]];
    RootDetectionPlugin* instance = [[RootDetectionPlugin alloc] init];
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    if ([@"checkRootOrJailbreak" isEqualToString:call.method]) {
        BOOL isJailbroken = [self checkJailbreak];
        result(@(isJailbroken));
    } else {
        result(FlutterMethodNotImplemented);
    }
}

- (BOOL)checkJailbreak {
    // 检查常见的越狱文件
    NSArray *jailbreakFilePaths = @[
        @"/Applications/Cydia.app",
        @"/Library/MobileSubstrate/MobileSubstrate.dylib",
        @"/bin/bash",
        @"/usr/sbin/sshd",
        @"/etc/apt",
        @"/private/var/lib/apt/",
        @"/Applications/Blackra1n.app",
        @"/Applications/FakeCarrier.app",
        @"/Applications/Icy.app",
        @"/Applications/IntelliScreen.app",
        @"/Applications/MxTube.app",
        @"/Applications/RockApp.app",
        @"/Applications/SBSettings.app",
        @"/Applications/WinterBoard.app",
        @"/Applications/barrel.app",
        @"/var/lib/cydia",
        @"/var/mobile/Library/SBSettings/Themes",
        @"/var/tmp/cydia.log",
        @"/var/log/syslog"
    ];

    for (NSString *path in jailbreakFilePaths) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            return YES;
        }
    }

    // 检查是否可以打开Cydia URL scheme
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cydia://package/com.example.package"]]) {
        return YES;
    }

    // 检查文件权限
    if ([[NSFileManager defaultManager] isWritableFileAtPath:@"/private"]) {
        return YES;
    }

    // 检查符号链接
    struct stat s;
    if (lstat("/Applications", &s) == 0) {
        if (s.st_mode & S_IFLNK) {
            return YES;
        }
    }

    // 检查注入的动态库
    int ret;
    Dl_info dylib_info;
    int (*func_stat)(const char*, struct stat*) = stat;
    if ((ret = dladdr(func_stat, &dylib_info))) {
        if (strcmp(dylib_info.dli_fname, "/usr/lib/system/libsystem_kernel.dylib") != 0) {
            return YES;
        }
    }

    return NO;
}

@end